#This fileset is required to set custom fields post-imaging that were specified in image_mappings.txt if client PC is NOT reimaged via a fileset
#This script will self-destruct after running

if ($env:PROCESSOR_ARCHITEW6432 -eq "AMD64") {
    #write-warning "Take me to 64-bit....."
    if ($myInvocation.Line) {
        &"$env:WINDIR\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile $myInvocation.Line
    }else{
        &"$env:WINDIR\sysnative\windowspowershell\v1.0\powershell.exe" -NonInteractive -NoProfile -file "$($myInvocation.InvocationName)" $args
    }
#exit $lastexitcode
}

function write_custom_field ($cf, $val) {
    $server_dns=(Get-ItemProperty -Path HKLM:\SOFTWARE\WOW6432Node\FileWave\WinClient -Name server).server
    $app_token=$Env:TOKEN
    $client_id=$Env:FWID
    $api="https://" + $server_dns + "/filewave/api/devices/v1/devices/" + $client_id
    $header=@{Authorization=$app_token}
    $data="{""custom_fields"": {""$cf"": ""$val""}}"

    Invoke-RestMethod -Method PATCH -Headers $header -Body $data -ContentType application/json -Uri $api
}

$custom_fields=(Get-ItemProperty -Path HKLM:\SOFTWARE\PSImage -Name CustomFields -ErrorAction SilentlyContinue).CustomFields

if ($custom_fields.length -gt 0){
    Write-Output "Found custom fields. Setting on server."
    $cf_count=$custom_fields.split(",").Count

    for ($i=0; $i -lt $cf_count; $i+=1) {
        $cf_field=$custom_fields.split(",")[$i]
        $cf_name=$cf_field.split(":")[0]
        $cf_value=$cf_field.split(":")[1]
        write_custom_field $cf_name "$cf_value"
    }
} else {
    Write-Output "No custom fields to set"
}

Remove-Item -Path c:\Windows\Temp\restore.done
Remove-Item -Path $MyInvocation.MyCommand.Source